/*
 * S18-分类管理
 * @author fsl - gonglong
 */
$(function () {

	var defaultPagingObj = {
		total : 20,
		pageSize : 10,
		page : 1
	};

	PAGE_DATA.pagingObj = $.extend(defaultPagingObj, PAGE_DATA.pagingObj);

	// 渲染页面-通用部分；
	commTemplUtil.initPage();
	// 渲染左侧菜单;
	commTemplUtil.initCommLeftMemu();

	// 获取 第一页 分类数据;
	getClassifyData(1);

	// "新增分类" 按钮 初始化事件;
	bindAddClassify();
});

/*
 *
 */
function getClassifyData(page) {

	var onClickObj = {
		onClick : function () {
			var clickPage = $(this).attr("data-page");
			getClassifyData(clickPage);
		}
	};

	var classifyTempl = _.template($('#classify_admin_templ').html());

	// 获取 分类信息列表
	$.ajax({
		url : PAGE_CONFIG.requestUrl.classifyS18Read,
		type : "get",
		data : {
			page : parseInt(page || 0),
			pageSize : parseInt(PAGE_DATA.pagingObj.pageSize || 0) ,
		},
		success : function (result) {
			setClassifyData(result.data, classifyTempl);

			//  更新翻页控件
			var tmpConf = $.extend(result.pagingConfData, onClickObj);
			commTemplUtil.initPaging("#comm-paging", tmpConf);

		},
		error : function () {
			commTemplUtil.showErrorDialog({
				title : '注意！',
				message : '获取 分类信息 失败！',
				ok_txt : "确定"
			});
		},
	});
};

/*
 *
 * 新增分类"按钮事件;
 */
function bindAddClassify() {

	var newClaTempl = _.template($("#add_classify_templ").html());

	$("#add-classify").on("click", function () {

		$.ajax({
			url : PAGE_CONFIG.requestUrl.classifyS18ReadOne,
			type : "get",
			data : {
				type : "0",
			},
			success : function (result) {
				var newClaTemplHtml = newClaTempl(result.data);
				createDialogNewClassify(newClaTemplHtml);
			},
			error : function () {
				commTemplUtil.showErrorDialog({
					title : '注意！',
					message : '新增分类-获取 "上级分类" 失败！',
					ok_txt : "确定"
				});
			}
		});

	});
};

/**
 * "新增分类"弹出框;
 */
function createDialogNewClassify(contentHtml) {

	var templ = _.template($("#classify_admin_templ").html());
	var dia = dialog({
			title : '新增分类',
			content : contentHtml,
			onshow : function () {
				var that = this;

				var newForm = $("#new-classify-form").validate({
						rules : {
							name : "required",
							parent_id : "required",
							sort : "required",
							display : "required"
						},
						errorPlacement : function (error, element) {
							if (element.attr("type") == "radio") {
								element.parent().parent().after($("<div class='error-line' />").append(error));
							} else {
								element.parent().after($("<div class='error-line' />").append(error));
							}
						}
					});

				// 新增分类-提交
				$("#submit-btn").on("click", function () {

					var flag = newForm.form();
					if (!flag) {
						return false;
					}

					var form = $("#new-classify-form");

					var nameVal = form.find("input[name='name']").val();
					var parentIdVal = form.find("[name='parent_id']").val();
					var sortVal = form.find("input[name='sort']").val();
					var displayVal = form.find("[name='display']:checked").val();

					$.ajax({
						url : PAGE_CONFIG.requestUrl.classifyS18Insert,
						type : "post",
						data : {
							name : nameVal,
							parent_id : parentIdVal,
							sort : sortVal,
							display : displayVal,
							_token : COMM_DATA.csrfToken
						},
						success : function (result) {
							that.remove();
							setClassifyData(result.data, templ);
						},
						error : function () {
							that.remove();
							commTemplUtil.showErrorDialog({
								title : "注意！",
								message : "新增分类 提交数据失败！",
								ok_txt : "确定"
							});
						}
					});

				});
			}
		});
	dia.showModal();

}

/***
 * 页面填充数据后, 绑定事件;
 */
function bindEvents(htmlObj) {

	var commBody = $("#commTabs_2_body");
	var classifyTempl = _.template($('#classify_admin_templ').html());

	// 展开/收缩 二级分类,
	commBody.find("[super]").on("click", function () {

		var superAttr = $(this).attr("data-id");
		var childrenObj = commBody.find("[super-id='" + superAttr + "']");

		if ($(this).attr("super") == "false") {
			// 展开
			$(this).attr("super", "true");
			// super-id
			childrenObj.show();
		} else {
			// 收缩
			childrenObj.hide();
			$(this).attr("super", "false");
		}
	});

	// 删除
	commBody.find(".sel-edit-del").on("click", function () {

		var dataId = $(this).parents("ul").attr("data-id");
		var currentPage = $("#comm-paging").attr("current-page");

		var deleDialog = dialog({
				id : "del-classify-dialog",
				title : "注意！",
				content : _.template($("#del-confirm").html()),
				onshow : function(){
					var diaObj = $("[id='content:del-classify-dialog']");
					diaObj.find("#ok-btn").on("click", function(){
						doDele();
					});
				}
			});

		deleDialog.showModal();

		function doDele() {
			$.ajax({
				url : PAGE_CONFIG.requestUrl.classifyS18Del,
				type : "delete",
				data : {
					id : dataId,
					page : currentPage,
					pageSize : PAGE_DATA.pagingObj.pageSize,
					_token : COMM_DATA.csrfToken
				},
				success : function (result) {
					deleDialog.remove();
					
					commBody.empty();
					setClassifyData(result.data, classifyTempl);
				},
				error : function () {
					deleDialog.remove();
					
					commTemplUtil.showErrorDialog({
						title : "注意！",
						message : "删除失败！",
						ok_txt : "确定"
					});
				
				}
			});
		};

		return false;
	});

	// 编辑,
	commBody.find(".sel-edit-btn").on("click", function () {

		var editClaTempl = _.template($("#add_classify_templ").html());
		var classifyTempl = _.template($('#classify_admin_templ').html());

		var classifyId = $(this).parents("ul").attr("data-id");
		var currentPage = $("#comm-paging").attr("current-page");

		$.ajax({
			url : PAGE_CONFIG.requestUrl.classifyS18ReadOne,
			type : "get",
			data : {
				id : classifyId,
				type : "2",
			},
			success : function (result) {
				var editClaTemplHtml = editClaTempl(result.data);

				var editDialog = dialog({
						title : '编辑分类',
						id : "edit-classify-dialog",
						content : editClaTemplHtml,
						onshow : function () {
							var that = this;

							// 编辑-提交
							$("#submit-btn").on("click", function () {
								var form = $("#new-classify-form");

								var nameVal = form.find("input[name='name']").val();
								var parentIdVal = form.find("[name='parent_id']").val();
								var sortVal = form.find("input[name='sort']").val();
								var displayVal = form.find("[name='display']:checked").val();
								var edit_id = form.find("[id='edit_id']").val();

								$.ajax({
									url : PAGE_CONFIG.requestUrl.classifyS18Update,
									type : "put",
									data : {
										id : edit_id,
										name : nameVal,
										parent_id : parentIdVal,
										sort : sortVal,
										display : displayVal,

										page : currentPage,
										pageSize : "7",

										_token : COMM_DATA.csrfToken
									},
									success : function (result) {
										setClassifyData(result.data, classifyTempl);
										that.remove();
									},
									error : function () {
										that.remove();
										
										commTemplUtil.showErrorDialog({
											title : "注意！",
											message : "更新 数据失败！",
											ok_txt : "确定"
										});
									}
								});
							});

						}
					});
				editDialog.showModal();
			},
			error : function () {
				commTemplUtil.showErrorDialog({
					title : "注意！",
					message : "'编辑' 获取数据失败！",
					ok_txt : "确定"
				});
			}
		});

		return false;
	});

	// 新增下级,
	commBody.find(".sel-new-btn").on("click", function () {

		// inferior
		var inferClaTempl = _.template($("#add_classify_templ").html());
		var classifyTempl = _.template($('#classify_admin_templ').html());
		var dataId = $(this).parents("ul").attr("data-id");
		console.log("dataId:" + dataId);

		$.ajax({
			url : PAGE_CONFIG.requestUrl.classifyS18ReadOne,
			type : "get",
			data : {
				id : dataId,
				type : "1"
			},
			success : function (result) {

				var inferClaTemplHtml = inferClaTempl(result.data);

				var editDialog = dialog({
						title : '新增下级',
						id : "new-infer-dialog",
						content : inferClaTemplHtml,
						onshow : function () {

							var that = this;
							
							// 表单验证, new-classify-form, [id='content:new-infer-dialog']
							var newInferForm = $("[id='content:new-infer-dialog']").find("form").validate({
									rules : {
										name : "required",
										parent_id : "required",
										sort : "required",
										display : "required"
									},
									errorPlacement : function (error, element) {
										if (element.attr("type") == "radio") {
											element.parent().parent().after($("<div class='error-line' />").append(error));
										} else {
											element.parent().after($("<div class='error-line' />").append(error));
										}
									}
								});
							
							

							// 新增下级-提交
							$("#submit-btn").on("click", function () {
								var form = $("#new-classify-form");
								
								var chkVal = newInferForm.form();
								if(!chkVal){
									return false;
								}
								
								var nameVal = form.find("input[name='name']").val();
								var parentIdVal = form.find("[name='parent_id']").val();
								var sortVal = form.find("input[name='sort']").val();
								var displayVal = form.find("[name='display']:checked").val();

								$.ajax({
									url : PAGE_CONFIG.requestUrl.classifyS18Insert,
									type : "post",
									data : {
										name : nameVal,
										parent_id : parentIdVal,
										sort : sortVal,
										display : displayVal,
										_token : COMM_DATA.csrfToken
									},
									success : function (result) {
										setClassifyData(result.data, classifyTempl);
										that.remove();
									},
									error : function () {
										that.remove(); 
										
										commTemplUtil.showErrorDialog({
											title : "注意！",
											message : "新增下级 提交失败！",
											ok_txt : "确定"
										});

									}
								});
							});

						}
					});
				editDialog.showModal();
			},
			error : function () {
				
				commTemplUtil.showErrorDialog({
					title : "注意！",
					message : "新增下级 获取数据失败！",
					ok_txt : "确定"
				});
				
			}
		});

		return false;
	});

};

/**
 * 生成-信息列表,
 */
function setClassifyData(data, templ) {
	var classifyTemplHtml = templ(data);
	$("#commTabs_2_body").html(classifyTemplHtml);
	bindEvents(templ);
};